//
//  ZMZWebContentView.m
//  zmzcloud
//
//  Created by 吴嘉佳 on 2017/7/26.
//  Copyright © 2017年 吴嘉佳. All rights reserved.
//  http://www.brighttj.com/ios/ios-webview-load-html-image-adaptive.html 图片自适应

#import "ZMZWebContentView.h"
#import "NSString+KHTML.h"


@interface ZMZWebContentView ()<WKNavigationDelegate,UIScrollViewDelegate,WKScriptMessageHandler>

@property (nonatomic, strong) WKWebViewConfiguration *configuration;

@end

@implementation ZMZWebContentView

- (instancetype)initWithFrame:(CGRect)frame{
    if (self = [super initWithFrame:frame]) {
        _webView = [[WKWebView alloc]initWithFrame:frame configuration:self.configuration];
        _webView.navigationDelegate = self;
        _webView.scrollView.delegate = self;
        [_webView setOpaque:NO];
        _webView.scrollView.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];
    }
    return self;
}

- (instancetype)initWithCoder:(NSCoder *)aDecoder {
    if (self = [super initWithCoder:aDecoder]) {
        _webView = [[WKWebView alloc]initWithFrame:self.bounds configuration:self.configuration];
        _webView.navigationDelegate = self;
        _webView.scrollView.delegate = self;
        [_webView setOpaque:NO];
        _webView.scrollView.backgroundColor = [UIColor colorWithHexString:@"f4f4f4"];
        _webView.scrollView.showsVerticalScrollIndicator = NO;
        _webView.scrollView.showsHorizontalScrollIndicator = NO;
        [self addSubview:_webView];
        [_webView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.equalTo(self).with.insets(UIEdgeInsetsMake(0, 0, 0, 0));
        }];
        [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    }
    return self;
}

-(WKWebViewConfiguration *)configuration {
    if (!_configuration) {
        _configuration = [[WKWebViewConfiguration alloc] init];
        
        _configuration.preferences = [[WKPreferences alloc] init];
        _configuration.preferences.minimumFontSize = 10;
        _configuration.preferences.javaScriptEnabled = YES;
        _configuration.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        _configuration.processPool = [[WKProcessPool alloc] init];
        
        _configuration.allowsInlineMediaPlayback = YES;
        //http://www.jianshu.com/p/255fdb8f60d3
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        _configuration.userContentController = wkUController;

        [self addJsInterfaces];
    }
    return _configuration;
}
/**
 更新userid到cookie中
 */
- (void)updateWebConfigCookieWithUserId:(NSString *)userId{
    NSString *cookieValue = [NSString stringWithFormat:@"document.cookie = 'userId=%@';",userId];
    WKUserContentController* userContentController = self.webView.configuration.userContentController;
    WKUserScript * cookieScript = [[WKUserScript alloc]
                                   initWithSource: cookieValue
                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    [userContentController addUserScript:cookieScript];
}


- (void)addJsInterfaces {
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_SHARE];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_PAY];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_CHAT];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_register];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_ShareContent];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_JumpPage];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_jumpChat];
    [_configuration.userContentController addScriptMessageHandler:self name:ZMZ_JSI_sendTel];
}

- (void)removeJsInterfaces {
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_SHARE];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_PAY];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_CHAT];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_register];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_ShareContent];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_JumpPage];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_jumpChat];
    [_configuration.userContentController removeScriptMessageHandlerForName:ZMZ_JSI_sendTel];
}

// 处理js接口事件
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if (self.delegate && [self.delegate respondsToSelector:@selector(webViewDidHandleMessageName:messageBody:)]) {
        [self.delegate webViewDidHandleMessageName:message.name messageBody:message.body];
    }
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        if (self.propressBlock) {
            self.propressBlock(self.webView.estimatedProgress);
        }
    } else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView)
        {
            if (self.titleBlock) {
                self.titleBlock(self.webView.title);
            }
        }
        else
        {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}


-(void)dealloc{
    if (_webView) {
        [self cleanWebviewCache];
        _webView.scrollView.delegate = nil;
        _webView.navigationDelegate = nil;
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    /*
    if (_configuration) {
        DLog(@"移除MessageHandler...");
        [self removeJsInterfaces];
    }
     */
}

#pragma mark -- private --
/**
 加载链接
 
 @param urlString 链接字符串
 */
- (void)loadRequestWithURLString:(NSString *)urlString
{
    if (_webView && StringNotEmpty(urlString)) {
        NSURL *url = [NSURL URLWithString:[NSString encodedStringWithUrlString:urlString]];
        [_webView loadRequest:[NSURLRequest requestWithURL:url]];
    }
}

/**
 加载html内容
 
 @param htmlString 内容字符串
 */
- (void)loadHtmlContentWithHtmlString:(NSString *)htmlString
{
    if (_webView && StringNotEmpty(htmlString)) {
        [_webView loadHTMLString:htmlString baseURL:nil];
    }
}


/**
 清除缓存
 */
- (void)cleanWebviewCache{
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"9.0")) {
        NSSet *types = [NSSet setWithArray:@[WKWebsiteDataTypeDiskCache,
                                             WKWebsiteDataTypeMemoryCache]];
        NSDate *dateFrom = [NSDate date];
        [[WKWebsiteDataStore defaultDataStore]removeDataOfTypes:types modifiedSince:dateFrom completionHandler:^{
            KLog(@"已删除缓存");
        }];
    }else{
        NSString *libaryPath = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).firstObject;
        NSString *cookiesFolderPath = [libaryPath stringByAppendingString:@"/Cookies"];
        [[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:nil];
    }
}

#pragma mark -- WKWebViewDelegate --

/**
 webview 开始加载
 */
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    if (self.didLoadBlock) {
        self.didLoadBlock(webView);
    }
    
    // 给web传userId
//    NSString *uid = [ZMZOverallDataManager manager].userInfo.userId;
//    NSString *getCookie = [NSString stringWithFormat:@"getCookie(\"%@\")",uid];

//    [webView evaluateJavaScript:getCookie completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//        DLog(@"%@",result);
//    }];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
    //    NSLog(@"内容开始加载");
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString *javaScript = [NSString stringWithFormat:@"var script = document.createElement('script');"
                  "script.type = 'text/javascript';"
                  "script.text = \"function ResizeImages() { "
                  "var myimg,oldwidth,oldheight;"
                  "var maxwidth=%.1f;"// 图片宽度
                  "for(i=0;i <document.images.length;i++){" "myimg = document.images[i];" "if(myimg.width > maxwidth){"
                  "myimg.width = maxwidth;"
                  "}"
                  "}"
                  "}\";"
                  "document.getElementsByTagName('head')[0].appendChild(script);",kScreenWidth - 20.0];
    [webView evaluateJavaScript:javaScript completionHandler:nil];
    [webView evaluateJavaScript:@"ResizeImages();" completionHandler:nil];
    
    // 页面内容加载完成
    if (self.finshLoadBlock) {
        self.finshLoadBlock(webView);
    }
    
    __weak typeof(self) weakSelf = self;
    [webView evaluateJavaScript:@"document.body.scrollHeight;" completionHandler:^(id _Nullable item, NSError * _Nullable error) {
        NSNumber *heightObj = (NSNumber *)item;
        // 高度回调
        if (weakSelf.contentHeightBlock) {
            weakSelf.contentHeightBlock(heightObj.doubleValue);
        }
    }];
}
- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    //    NSLog(@"页面加载失败");
    if (self.loadErrorBlock) {
        self.loadErrorBlock(webView, error);
    }
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    //    NSLog(@"页面加载失败");
    if (self.loadErrorBlock) {
        self.loadErrorBlock(webView, error);
    }
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
    //    NSLog(@"接收到服务器跳转请求的代理");
}
/*
 - (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
 NSLog(@"在收到响应后，决定是否跳转的代理");
 
 decisionHandler(WKNavigationResponsePolicyAllow);
 }
 */


-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSURL *URL = navigationAction.request.URL;
    NSLog(@"%@",URL);
    // isPolicy 是否加载网页，默认为YES
    BOOL isPolicy = YES;
    if (self.shouldStartLoadBlock) {
        isPolicy = self.shouldStartLoadBlock(webView,navigationAction.request);
    }
    isPolicy?decisionHandler(WKNavigationActionPolicyAllow) :decisionHandler(WKNavigationActionPolicyCancel);
}
// 禁止缩放
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView {
    return nil;
}

/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
